package Core

import (
	"database/sql"
	"fmt"
	"reflect"
)

// map row data to string
func rowMapper(rows *sql.Rows) ([]map[string]string, error) {
	cols, e := rows.Columns()
	if e != nil {
		return nil, e
	}
	tmpItf := make([]interface {}, len(cols))
	for i, _ := range tmpItf {
		var itr interface {}
		tmpItf[i] = &itr
	}
	// set returning result
	rs := make([]map[string]string, 0)
	for rows.Next() {
		rows.Scan(tmpItf...)
		rowRst := make(map[string]string)
		// make all column values to string and append to result
		for i, col := range tmpItf {
			str := fmt.Sprint(reflect.Indirect(reflect.ValueOf(col)).Interface())
			if str == "<nil>" {
				str = ""
			}
			rowRst[cols[i]] = str
		}
		rs = append(rs, rowRst)
	}
	return rs, nil
}

// parse sql.Result to int64
func resultParser(rs sql.Result) (int64, error) {
	i, e := rs.LastInsertId()
	if e != nil {
		return -1, e
	}
	if i < 1 {
		i, e = rs.RowsAffected()
		if e != nil {
			return -1, e
		}
	}
	return i, nil
}
